
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[EBAS_SP_HENT_GRUPPE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[EBAS_SP_HENT_GRUPPE]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [DBO].[EBAS_SP_HENT_GRUPPE] 
	@session varchar(255),
	@navn varchar(255) = NULL,
	@studGuid varchar(255) = NULL
WITH ENCRYPTION
AS
	DECLARE @rettighed int,
		@antal int, 
		@guid uniqueidentifier
	
	SET NOCOUNT ON
	SET @antal = 0

	CREATE TABLE #temp ( rett int )
	INSERT INTO #temp (rett)
	EXEC EBAS.DBO.EBAS_SP_SIKKERHED_VERIFICER_SESSION @session	

	SET @rettighed = (SELECT IsNull(MAX(rett),0) FROM #temp)
	
	IF 0 < @rettighed 
	BEGIN
		SET @antal = (SELECT COUNT(*) FROM EBAS_GRUPPE)
		
		IF @navn IS NULL AND @studGuid IS NULL
			SELECT	GUID, NAVN, START_TID, SLUT_TID, STED, @antal AS ANTAL,
				BEMAERKNING, EJERFORHOLD_GUID
			FROM	EBAS_GRUPPE
		ELSE IF @navn IS NOT NULL AND @studGuid IS NULL
			SELECT	GUID, NAVN, START_TID, SLUT_TID, STED, 1 AS ANTAL,
				BEMAERKNING, EJERFORHOLD_GUID
			FROM	EBAS_GRUPPE
			WHERE 	NAVN = @navn
		ELSE IF @studGuid IS NOT NULL
			SELECT	GUID, NAVN, START_TID, SLUT_TID, STED, 1 AS ANTAL,
				BEMAERKNING, EJERFORHOLD_GUID
			FROM	EBAS_GRUPPE
			WHERE 	GUID IN ( 
				SELECT GRUPPE_GUID 
				FROM EBAS_GRUPPE_STUDERENDE
				WHERE STUDERENDE_GUID = @studGuid)
	END
	ELSE			
		SELECT	GUID, NAVN, START_TID, SLUT_TID, STED, 0 as ANTAL,
			BEMAERKNING, EJERFORHOLD_GUID
		FROM	EBAS_GRUPPE
		WHERE	GUID IS NULL
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
